<template>
    <el-card class="template-group" v-loading="loading">
        <div class="top">
            <div class="title">已选{{ chooseData.length }}个</div>
            <div class="item-list">
                <el-button
                    v-for="(item, i) in chooseData"
                    :key="i"
                    class="relative"
                    size="medium">
                    {{ item.course }}
                    <i class="el-icon-close absolute top-0 right-0" @click="onDelChoose(item, i)"></i>
                </el-button>
            </div>

            <div class="search">
                <el-input
                    v-model="form.name"
                    size="small"
                    class="input-width mr-2"
                    placeholder="请输入学习路径/学习主题进行搜索"></el-input>
                <el-button size="small" type="primary" @click="fetchData">搜索</el-button>
                <el-button size="small" type="primary" @click="onReset">重置</el-button>
            </div>
        </div>

        <div class="content" v-if="my.company_id">
            <div class="title">自建的内容</div>

            <div class="selection" v-for="(item, i) in companyData" :key="i">
                <!-- 主题模块 -->
                <div class="item">
                    <div class="item-title">
                        <div class="bg">
                            {{ item.course_template_name ? item.course_template_name : '单个学习主题' }}
                        </div>
                    </div>
                    <div>
                        <div class="sum">
                            可选工作场景主题 {{ item.child }} 个
                            <i v-if="item.course_template_describe" class="line"></i>
                            {{ item.course_template_describe }}
                        </div>
                    </div>

                    <div class="check-box">
                        <el-checkbox
                            @change="moreSelect($event, item)"
                            v-model="item.checked">全选</el-checkbox>
                    </div>

                    <el-collapse v-model="activeNames">
                        <el-collapse-item
                            v-for="(cot, c) in item.label_list"
                            :key="c"
                            :name="cot.index">
                            <template slot="title">
                                <el-checkbox
                                    @change="handleCheckAll($event, cot, item)"
                                    v-model="cot.checked"></el-checkbox>
                                {{ cot.label }} {{ cot.content_list.length }} 个
                            </template>

                            <div class="collapse-box">
                                <div v-for="(btn, b) in cot.content_list" :key="b">
                                    <el-tooltip placement="bottom-start" :open-delay="1000" :enterable="false">
                                        <div
                                            :class="`collapse-item ${ btn.checked ? 'active' : '' }`"
                                            @click="onSelect(btn, cot, item)">{{ btn.course }}</div>
                                        <div class="content" slot="content">
                                            <GroupComponent :detailData="btn"/>
                                        </div>
                                    </el-tooltip>
                                </div>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </div>
        </div>

        <div class="content">
            <div class="title">来自msup提供的内容</div>

            <div class="selection" v-for="(item, i) in adminData" :key="i">
                <!-- 主题模块 -->
                <div class="item">
                    <div class="item-title">
                        <div class="bg">
                            {{ item.course_template_name ? item.course_template_name : '单个学习主题' }}
                        </div>
                    </div>
                    <div>
                        <div class="sum">
                            可选工作场景主题 {{ item.child }} 个
                            <i v-if="item.course_template_describe" class="line"></i>
                            {{ item.course_template_describe }}
                        </div>
                    </div>

                    <div class="check-box">
                        <el-checkbox
                            @change="moreSelect($event, item)"
                            v-model="item.checked">全选</el-checkbox>
                    </div>

                    <el-collapse v-model="activeNames">
                        <el-collapse-item
                            v-for="(cot, c) in item.label_list"
                            :key="c"
                            :name="cot.index">
                            <template slot="title">
                                <el-checkbox
                                    @change="handleCheckAll($event, cot, item)"
                                    v-model="cot.checked"></el-checkbox>
                                {{ cot.label }} {{ cot.content_list.length }} 个
                            </template>

                            <div class="collapse-box">
                                <div v-for="(btn, b) in cot.content_list" :key="b">
                                    <el-tooltip placement="bottom-start" :open-delay="1000" :enterable="false">
                                        <div
                                            :class="`collapse-item ${ btn.checked ? 'active' : '' }`"
                                            @click="onSelect(btn, cot, item)">{{ btn.course }}</div>
                                        <div class="content" slot="content">
                                            <GroupComponent :detailData="btn"/>
                                        </div>
                                    </el-tooltip>
                                </div>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </div>
        </div>

        <div class="text-center mt-4">
            <el-button type="primary" @click="onCreateData">保 存</el-button>
        </div>
    </el-card>
</template>

<script>
import { Collapse, CollapseItem, Tooltip } from 'element-ui';
import GroupComponent from './GroupComponent';

export default {
    components: {
        ElCollapse: Collapse,
        ElCollapseItem: CollapseItem,
        ElTooltip: Tooltip,
        GroupComponent,
    },
    data() {
        return {
            loading: false,
            activeNames: [],

            adminData: [],
            companyData: [],

            chooseData: [],

            form: {
                companyId: '',
                name: '',
            },

            templateData: {
                title: '',
                describe: '',
                is_template: false,
                content_list: [],
            },
            content_list: [],
        };
    },
    computed: {
        my() {
            return this.$store.state.my;
        },
    },
    methods: {
        /**
         * 删除已选中的数据
         *
         * @params e 选中的数据
         * @params i 数据的下标
        */
        onDelChoose(e, i) {
            const chooseData = [...this.chooseData];
            chooseData.splice(i, 1);

            this.delChooseFn(e, 'adminData');
            this.delChooseFn(e, 'companyData');

            this.chooseData = chooseData;
        },
        delChooseFn(e, dataText) {
            const arrData = this[dataText];

            const first = {...e};
            delete first.checked;
            for (const item of arrData) {
                for (const val of item.label_list) {
                    for (const obj of val.content_list) {
                        const second = {...obj};
                        delete second.checked;

                        // 没有唯一id，比对数据字符串,是否是同一数据
                        if (JSON.stringify(first) === JSON.stringify(second)) {
                            obj.checked = false;
                            if (val.checked) val.checked = false;
                            if (item.checked) item.checked = false;
                        }
                    }
                }
            }

            this[dataText] = arrData;
        },

        /**
         * 选中数据
         * @params e 选中的数据
         * @params child 子级数据
         * @params parent 父级数据
        */
        onSelect(e, child, parent) {
            const chooseData = this.chooseData;

            if (!chooseData.length) {
                chooseData.push(e);
                e.checked = true;
            } else {
                let index = 0;
                const first = {...e};
                delete first.checked;

                chooseData.forEach((v, i) => {
                    const second = {...v};
                    delete second.checked;

                    // 没有唯一id，比对数据字符串,是否是同一数据
                    if (JSON.stringify(first) === JSON.stringify(second)) index = i + 1;
                });

                if (index) {
                    chooseData.splice(index - 1, 1);
                    e.checked = false;
                } else {
                    chooseData.push(e);
                    e.checked = true;
                }
            }

            this.checkedFn(child, 'content_list');
            this.checkedFn(parent, 'label_list');
        },

        /**
         * 场景全选
         * @params e 是否选中
         * @params parent 父级数据
        */
        moreSelect(e, parent) {
            const arrData = parent.label_list;

            if (arrData && arrData.length) {
                if (e) {
                    parent.checkedArr = arrData;
                } else parent.checkedArr = [];

                for (const item of arrData) {
                    this.handleCheckAll(e, item);
                    item.checked = e;
                }
            }
        },

        /**
         * 主题全选
         *
         * @params e 是否选中
         * @params child 子级数据
         * @params parent 父级数据
        */
        handleCheckAll(e, child, parent) {
            const arrData = child.content_list || [];

            let chooseData = [...this.chooseData];
            if (!chooseData.length && e) chooseData = [...arrData];
            if (chooseData.length) {
                for (const item of arrData) {
                    const first = {...item};
                    delete first.checked;
                    let index = 0;

                    chooseData.forEach((v, i) => {
                        const second = {...v};
                        delete second.checked;

                        // 没有唯一id，比对数据字符串,是否是同一数据
                        if (JSON.stringify(first) === JSON.stringify(second)) return index = i + 1;
                    });

                    if (!index && e) chooseData.push(first);
                    if (index && !e) chooseData.splice(index - 1, 1);
                }
            }

            child.content_list.map(item => {
                item.checked = e;
                return item;
            });

            if (e) {
                child.checkedArr = arrData;
            } else child.checkedArr = [];

            this.chooseData = chooseData;

            if (parent) this.checkedFn(parent, 'label_list');
        },

        /**
         * 设置全选的checkbox选中状态
        */
        checkedFn(obj, arrText) {
            let pCheck = 0;
            const pArr = obj[arrText] || [];

            for (const item of pArr) {
                if (item.checked) pCheck += 1;
            }

            if (!pCheck || (pCheck && pCheck !== pArr.length)) obj.checked = false;
            if (pCheck === pArr.length) obj.checked = true;
        },

        /**
         * 重置搜索条件
        */
        onReset() {
            this.form.name = '';
            this.activeNames = [];
            this.fetchData();
        },

        /**
         * 获取数据
        */
        fetchData() {
            if (this.my && this.my.company_id) this.form.companyId = this.my.company_id;

            this.loading = true;
            API.get('template/content', {params: this.form}).then(res => {
                let adminData = res.admin_list || [];
                let companyData = res.company_list || [];

                adminData = this.fetchDataOption(adminData);
                companyData = this.fetchDataOption(companyData);

                this.adminData = adminData;
                this.companyData = companyData;
            }).finally(() => this.loading = false);
        },

        // 数据结构处理
        fetchDataOption(vItem) {
            let num = 0;
            const chooseData = this.chooseData;

            const vData = [...vItem];

            for (const item of vData) {
                if (!item.label_list || !item.label_list.length) continue;
                item.child = 0;
                item.checked = false;
                item.checkedArr = [];

                /**
                 * 已选中的子级数量
                 * */
                let itemCheckNum = 0;
                for (const val of item.label_list) {
                    if (!val.content_list || !val.content_list.length) continue;

                    val.checked = false;
                    val.checkedArr = [];

                    val.index = num;
                    num++;
                    item.child += val.content_list.length;

                    /**
                     * 已选中的数量
                     * */
                    let valCheckNum = 0;
                    val.content_list = val.content_list.map(obj => {
                        obj.checked = false;

                        if (!chooseData || !chooseData.length) return obj;

                        // 当chooseData有数据时，即是搜索时获取数据
                        const first = {...obj};
                        delete first.checked;
                        for (const v of chooseData) {
                            const second = {...v};
                            delete second.checked;

                            // 没有唯一id，比对数据字符串,是否是同一数据
                            if (JSON.stringify(first) === JSON.stringify(second)) {
                                obj.checked = true;
                                valCheckNum += 1;
                            }
                        }

                        return obj;
                    });

                    if (valCheckNum === val.content_list.length) {
                        val.checked = true;
                        itemCheckNum += 1;
                    }
                }

                item.checked = !!(itemCheckNum === item.label_list.length);
            }

            return vData;
        },

        /**
         * 数据是否选中
         * @param val 数据，<object>
         * @return className string
        */
        selected(val) {
            if (!val) return '';
            const chooseData = this.chooseData;
            for (const item of chooseData) {
                const first = {...item};
                const second = {...val};

                // 数据没有唯一id，进行数据字符串比对
                if (JSON.stringify(first) === JSON.stringify(second)) return 'active';
            }
            return '';
        },

        /**
         * 获取模板数据
        */
        async fetchTemplate() {
            this.loading = true;
            this.templateData = await API.get(`template/${this.id}`);
            this.loading = false;
        },

        /**
         * 生成数据
        */
        onCreateData() {
            const form = {...this.templateData};
            let chooseData = [...this.chooseData];

            chooseData = chooseData.map(item => {
                const obj = {
                    label: item.label,
                    course: item.course,
                    describe: item.describe,
                    detail: item.detail,
                    capability: item.capability,
                    benefit: item.benefit,
                    list: item.list,
                    note: item.note,
                };
                return obj;
            });

            let method = 'post';
            let url = 'template';

            if (this.id) {
                method = 'put';
                url = `template/${this.id}`;

                const list = [...form.content_list];
                form.content_list = [...list, ...chooseData];
            } else form.content_list = chooseData;

            this.loading = true;
            API[method](url, form).then(res => {
                $ele.$message.success('保存成功');
                let id;
                if (typeof res === 'number') id = res;

                if (this.id) id = this.id;

                this.$router.replace({
                    name: 'Template.Detail',
                    query: {
                        id: id,
                    },
                });
            }).finally(() => this.loading = false);
        },

        overTime(e) {
            e.show = !e.show;
        },
    },
    mounted() {
        this.fetchData();

        const id = this.$route.params.id;

        let data = sessionStorage.getItem('templateData');

        if (data) {
            data = JSON.parse(data);
            this.templateData.title = data.title;
            this.templateData.describe = data.describe;
        }

        if (id) {
            this.id = id;
            this.fetchTemplate();
        }
    },

    destroyed() {
        sessionStorage.removeItem('templateData');
    },
};
</script>

<style lang="scss">
$marginL: 130px;
$color: rgb(64, 158, 255);
$color2: rgb(221, 223, 230);

.template-group {
    .input-width {
        max-width: 300px;
    }

    .top {
        margin-left: $marginL;

        .title {
            margin-bottom: 25px;
        }

        .item-list {
            height: 130px;
            overflow-y: auto;

            .el-button {
                padding: 12px 45px;
                border-radius: 5px;
                margin: 0 10px 10px 0;

                &:focus, &:hover {
                    color: inherit;
                    background: white;
                    border: 1px solid #DCDFE6;
                }
            }

            .el-button+.el-button {
                margin-left: 0;
            }

            i {
                width: 27px;
                height: 27px;
                margin: -1px -1px 0 0;
                text-align: right;
                color: white;
                font-size: 16px;
                font-weight: 600;
                border-radius: 0 5px 0 0;
                background: linear-gradient(45deg, #fff 0%, #fff 49%, #ff445c 50%, #ff445c 100%);
            }
        }

        .search {
            border-top: 1px solid $color2;
            padding-top: 50px;
            margin-top: 50px;
        }
    }

    .content {
        margin-top: 30px;

        .check-box {
            margin-bottom: 15px;
        }

        .el-checkbox__inner {
            border-radius: 50%;
        }

        .el-checkbox:last-of-type {
            margin-right: 10px;
            padding-left: 10px;
        }

        .el-checkbox__input .el-checkbox__inner::after {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 6px;
            height: 6px;
            border: none;
        }

        .el-checkbox__input.is-checked .el-checkbox__inner {
            background-color: white;

            &::after {
                background: #409EFF;
                border-radius: 50%;
            }
        }

        .el-collapse-item__header,
        .el-collapse,
        .el-collapse-item__wrap {
            border: none;
        }

        .el-collapse-item__wrap {
            overflow: visible;
        }

        .el-collapse-item__header {
            color: #2d70ae;
            font-size: 20px;
            padding-right: 25px;
            box-sizing: border-box;
        }

        .el-collapse-item {
            margin-bottom: 10px;
        }

        .el-collapse-item__arrow {
            width: 30px;
            height: 30px;
            background: url('~@/assets/images/template/open.png') no-repeat;
            background-size: contain;
        }

        .el-collapse-item__arrow.is-active {
            background: url('~@/assets/images/template/close.png') no-repeat;
            background-size: contain;
            transform: rotate(0);
        }

        .el-icon-arrow-right:before {
            content: '';
        }

        .el-collapse-item__content {
            padding-top: 10px;
            padding-right: 10px;
            padding-bottom: 0;
        }

        .title {
            font-size: 14px;
            color: rgb(155, 155, 155);
            padding: 14px 0 14px $marginL;
            background: rgb(250, 250, 250);
            margin-bottom: 17px;
        }

        .selection {
            padding: 24px 100px 20px 130px;
            box-sizing: border-box;
            box-shadow: 0 0 4px 1px $color2;
            margin: 10px 0;
        }

        .item {
            &-title {
                display: flex;
                align-items: flex-end;
                margin-bottom: 15px;

                .bg {
                    font-size: 40px;
                    color: #606266;
                    margin-right: 26px;
                }

            }

            .sum {
                font-size: 14px;
                color: #b0b4bc;
                margin-bottom: 30px;

                .line {
                    width: 100px;
                    display: inline-block;
                    margin: 0 4px 3px 4px;
                    border-top: 2px solid #cecdcd;
                }
            }

            .collapse-box {
                display: flex;
                flex-wrap: wrap;
            }

            .collapse-item {
                display: flex;
                justify-content: center;
                align-items: center;
                min-width: 230px;
                min-height: 44px;
                text-align: center;
                box-sizing: border-box;
                padding: 0 12px;
                border: 1px solid $color2;
                border-radius: 5px;
                margin-right: 25px;
                margin-bottom: 23px;
                cursor: pointer;

                &.active {
                    background: $color;
                    color: white;
                }

                &:hover {
                    box-shadow: 0 0 8px 2px $color2;
                }
            }
        }
    }

    .el-collapse-item__header {
        background: rgba($color: #2d70ae, $alpha: .05);
    }
}

.el-tooltip__popper.is-dark {
    background: rgba($color: #36383c, $alpha: .8);
}
</style>
